/*
 * This file is part of APNdroid.
 *
 * APNdroid is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * APNdroid is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with APNdroid. If not, see <http://www.gnu.org/licenses/>.
 */

package com.google.code.packetkiller;

import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.google.code.packetkiller.R;
import com.google.code.japndroid.PacketKillerConstants;
import com.google.code.japndroid.PacketKillerUtils;
import com.google.code.packetkiller.dao.DaoFactory;
import com.google.code.packetkiller.preferences.Prefs;

import 	android.content.ContentResolver;
import android.provider.Settings;
import android.os.IHardwareService;
import android.os.ServiceManager;
/**
 * @author Pavlov Dmitry <pavlov.dmitry.n@gmail.com>
 */
public class StatusWidget extends AppWidgetProvider {

    @Override
    public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);
    	
        Log.v("PAKCKET KILLER",intent.getAction());
    	
        AppWidgetManager manager = AppWidgetManager.getInstance(context);
        int[] widgetIds = manager.getAppWidgetIds(new ComponentName(context, StatusWidget.class));
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
        
        if (	PacketKillerConstants.WIFI_STATUS_CHANGE_REQUEST.equals(intent.getAction()) ){
            views.setImageViewResource(R.id.widgetCanvas5,R.drawable.icon_wait_wifi);
            manager.updateAppWidget(widgetIds, views);
           
        }else if( /* PacketKillerConstants.WIFI_STATUS_CHANGE_DONE.equals(intent.getAction()) || */
        		"android.net.wifi.WIFI_STATE_CHANGED".equals(intent.getAction())) {
        	/*
        	 * Bundle bundle = intent.getExtras();
        	 
        	boolean status = true;
        	if( bundle != null ){
        		status = bundle.getBoolean("enable");
        	}else{
        		status = PacketKillerUtils.isWifiConnectedOrConnecting(context);
        	}*/
        	boolean status = PacketKillerUtils.isWifiConnectedOrConnecting(context);
        	createWifiView(views,context,status);
            manager.updateAppWidget(widgetIds, views);
            
        }else if( PacketKillerConstants.BLUETOOTH_STATUS_CHANGE_REQUEST.equals(intent.getAction()) ){
            views.setImageViewResource(R.id.widgetCanvas3,R.drawable.icon_wait_bt);
            manager.updateAppWidget(widgetIds, views);
            
        }else if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(intent.getAction()) 
        		// BluetoothAdapter.BLUETOOTH_STATUS_CHANGE_DONE.equals(intent.getAction()) ||
        		//BluetoothAdapter.ACTION_STATE_CHANGED.equals(intent.getAction())
        		){
        	/*
        	Bundle bundle = intent.getExtras();
        	boolean status = true;
        	if( bundle == null ){
        		status = PacketKillerUtils.isBlueToothActive();
        	}else{
        		status = bundle.getBoolean("enable");
        	}*/
        	createBlueToothView(views,context,PacketKillerUtils.isBlueToothActive());
            manager.updateAppWidget(widgetIds, views);
            
        }else if(PacketKillerConstants.TASK_KILL_ALL_REQUEST.equals(intent.getAction()) ){
    		Toast.makeText(context, "停止中", Toast.LENGTH_SHORT).show();
            views.setImageViewResource(R.id.widgetCanvas5,R.drawable.icon_wait_task);
            manager.updateAppWidget(widgetIds, views);

        }else if(PacketKillerConstants.TASK_KILL_ALL_DONE.equals(intent.getAction()) ){
          	createTaskView(views,context);
            manager.updateAppWidget(widgetIds, views);
        }else if(PacketKillerConstants.MASTER_SYNCAUTOMATICALLY_CHANGE_REQUEST.equals(intent.getAction()) ){
        	views.setImageViewResource(R.id.widgetCanvas4,R.drawable.icon_wait_sync);
        	manager.updateAppWidget(widgetIds, views);
        }else if(PacketKillerConstants.MASTER_SYNCAUTOMATICALLY_CHANGE_DONE.equals(intent.getAction()) ){
          	createMasterSyncAutomaticallyView(views,context);
            manager.updateAppWidget(widgetIds, views);
        // DISPLAY Brightness
        }else if(PacketKillerConstants.DISPLAY_STATUS_CHANGE_REQUEST.equals(intent.getAction())) {  
        	
        	try {
        		
				int val = Settings.System.getInt(context.getContentResolver() , Settings.System.SCREEN_BRIGHTNESS);
				Log.v("PACKET KILLER","Brightness is " + val);

	        	int brightpref = 0; 
	        	int iconId = R.drawable.icon_on_display;
	        	if( val <= 10 ){
	        		brightpref = 255;
	        	}else{
	        		brightpref = 5;
	        		iconId = R.drawable.icon_off_display;
	        	}
	        	IHardwareService hardware = IHardwareService.Stub.asInterface(	ServiceManager.getService("hardware"));
	        	hardware.setScreenBacklight(brightpref);
	        	//IPowerManager pm = IPowerManager.Stub.asInterface(ServiceManager.getService(Context.POWER_SERVICE));
                //pm.setBacklightBrightness(brightpref);
	        	//android.provider.Settings.System.putInt(context.getContentResolver(),"screen_brightness_mode",0);
	        	android.provider.Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, brightpref);           
	        	views.setImageViewResource(R.id.widgetCanvas4,iconId);
	        	manager.updateAppWidget(widgetIds, views);
	        	
			} catch (Exception e) {
				Toast.makeText(context, "Error "+e.getMessage(), Toast.LENGTH_LONG).show();
				e.printStackTrace();
			}finally{
				
			}

        	
        }else if(PacketKillerConstants.DISPLAY_STATUS_CHANGE_DONE.equals(intent.getAction())) {
        	
        	ContentResolver arg0 = context.getContentResolver(); 
        	String arg1 = Settings.System.SCREEN_BRIGHTNESS; 
        	int arg2 = 0; 
        	Settings.System.putInt(arg0, arg1, arg2); 
        	                 
            Bundle extras = intent.getExtras();
            float val = 0.0f;
            if (extras != null) {
            	val = extras.getFloat("screenBrightness");
            }
            int iconId = (val < 1.0f) ? R.drawable.icon_wait_display : R.drawable.icon_off_display;
            views.setImageViewResource(R.id.widgetCanvas4,iconId);
            manager.updateAppWidget(widgetIds, views);

        }else 
        /* 上にpacketkillerの機能を追加*/
        if (Constants.STATUS_CHANGED_MESSAGE.equals(intent.getAction())) {
            Bundle extras = intent.getExtras();
            if (extras != null && extras.containsKey(Constants.STATUS_EXTRA)) {
                boolean isNetEnabled = extras.getBoolean(Constants.STATUS_EXTRA);
                
                //AppWidgetManager manager = AppWidgetManager.getInstance(context);
                //int[] widgetIds = manager.getAppWidgetIds(new ComponentName(context, StatusWidget.class));
                showWidget(context, manager, widgetIds, isNetEnabled);
                storeStatus(context, isNetEnabled);
            }
        } else if (Constants.STATUS_SWITCH_IN_PROGRESS_MESSAGE.equals(intent.getAction())) {
            Log.d(Constants.APP_LOG, "sending switch in progress broadcast received in widget handler");
            //AppWidgetManager manager = AppWidgetManager.getInstance(context);
            //int[] widgetIds = manager.getAppWidgetIds(new ComponentName(context, StatusWidget.class));
            showInProgressWidget(context, manager, widgetIds);
        }
    }



	private void storeStatus(Context context, boolean netEnabled) {
        Prefs prefs = new Prefs(context);
        prefs.setLastStatus(netEnabled);
    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] ints) {
        super.onUpdate(context, appWidgetManager, ints);
        
        Prefs prefs = new Prefs(context);
        boolean isNetEnabled;
        if (prefs.hasLastStatus()) {
            isNetEnabled = prefs.isLastStatusConnected();
        } else {
            isNetEnabled = DaoFactory.getDao(context).isDataEnabled();
        }
        showWidget(context, appWidgetManager, ints, isNetEnabled);
    }

    private void showWidget(Context context, AppWidgetManager manager, int[] widgetIds, boolean status) {
        RemoteViews views = createRemoteViews(context, status);
        manager.updateAppWidget(widgetIds, views);
    }

    private void showInProgressWidget(Context context, AppWidgetManager manager, int[] widgetIds) {
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
        int iconId = R.drawable.data_in_progress;
        views.setImageViewResource(R.id.widgetCanvas, iconId);
        //views.setTextViewText(R.id.widgetButton, "");
        manager.updateAppWidget(widgetIds, views);
    }
    
    // 3G ON/OFF
    private RemoteViews create3gView(RemoteViews views,Context context, boolean status) {

        int iconId = status ? R.drawable.icon_on_3g : R.drawable.icon_off_3g;
        views.setImageViewResource(R.id.widgetCanvas, iconId); // iconId
        Intent msg = new Intent(Constants.CHANGE_STATUS_REQUEST);
        PendingIntent intent = PendingIntent.getBroadcast(context, 1 , msg, PendingIntent.FLAG_UPDATE_CURRENT);
        views.setOnClickPendingIntent(R.id.widgetCanvas, intent);
        return views;
    }
    // WiFi ON/OFF
    private RemoteViews createWifiView(RemoteViews views,Context context,boolean enable) {

        int iconId = enable ? R.drawable.icon_on_wifi : R.drawable.icon_off_wifi;
        views.setImageViewResource(R.id.widgetCanvas2, iconId); 
        
        Intent msg = new Intent(PacketKillerConstants.WIFI_STATUS_CHANGE_REQUEST);
        PendingIntent intent = PendingIntent.getBroadcast(context, 2 , msg, PendingIntent.FLAG_UPDATE_CURRENT);
        views.setOnClickPendingIntent(R.id.widgetCanvas2, intent);
        return views;
    }
    
    // BLUE TOOTH
    private RemoteViews createBlueToothView(RemoteViews views,Context context,boolean enable) {
    	boolean isBlueToothEnable  = PacketKillerUtils.canBlueToothAvailable() ;
    	int iconId = R.drawable.icon_off_bt;
        if( isBlueToothEnable ){
        	iconId = enable ? R.drawable.icon_on_bt : R.drawable.icon_off_bt;

        	Intent msg = null;
        	if(!enable){
        		msg = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        	}else{
        		msg = new Intent(PacketKillerConstants.BLUETOOTH_REQUEST_DISENABLE);
        	}
        	PendingIntent intent = PendingIntent.getBroadcast(context, 3 , msg, PendingIntent.FLAG_UPDATE_CURRENT);
        	views.setOnClickPendingIntent(R.id.widgetCanvas3, intent); 
        }else{
        	
        }
    	views.setImageViewResource(R.id.widgetCanvas3, iconId); 
        return views;
    }
    // Display brightness up / down
    private RemoteViews __createDisplayView(RemoteViews views,Context context) {
    	
    	Log.v("PACKET KILLER","CALL CREATE DISPLAY VIEW");
    	
        int iconId = true ? R.drawable.icon_on_display : R.drawable.icon_off_display;
        views.setImageViewResource(R.id.widgetCanvas4, iconId); 
        
        Intent msg = new Intent(PacketKillerConstants.DISPLAY_STATUS_CHANGE_REQUEST);
        PendingIntent intent = PendingIntent.getBroadcast(context, 4 , msg, PendingIntent.FLAG_UPDATE_CURRENT);
        views.setOnClickPendingIntent(R.id.widgetCanvas4, intent); 
        return views;
    }
    // Master Sync Automatically
    private void createMasterSyncAutomaticallyView(RemoteViews views,
			Context context) {
		// TODO Auto-generated method stub
    	boolean status = android.content.ContentResolver.getMasterSyncAutomatically();
    	 int iconId = status ? R.drawable.icon_on_sync : R.drawable.icon_off_sync;
         views.setImageViewResource(R.id.widgetCanvas4, iconId);
         
         Intent msg = new Intent(PacketKillerConstants.MASTER_SYNCAUTOMATICALLY_CHANGE_REQUEST);
         msg.putExtra("enable",!status);
         PendingIntent intent = PendingIntent.getBroadcast(context, 1 , msg, PendingIntent.FLAG_UPDATE_CURRENT);
         views.setOnClickPendingIntent(R.id.widgetCanvas4, intent);

	}
    // TASK KILL ALL
    private RemoteViews createTaskView(RemoteViews views,Context context) {

    	views.setImageViewResource(R.id.widgetCanvas5, R.drawable.icon_on_task); 
        
        Intent msg = new Intent(PacketKillerConstants.TASK_KILL_ALL_REQUEST);
        PendingIntent intent = PendingIntent.getBroadcast(context, 5 , msg, PendingIntent.FLAG_UPDATE_CURRENT);
        views.setOnClickPendingIntent(R.id.widgetCanvas5, intent); 
        return views;
    }
    private RemoteViews createRemoteViews(Context context, boolean status) {
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
    	create3gView(views,context, status);
        boolean isWifiConnectedOrConnecting = PacketKillerUtils.isWifiConnectedOrConnecting(context);
    	createWifiView(views,context,isWifiConnectedOrConnecting);
    	boolean isBlueToothActive = PacketKillerUtils.isBlueToothActive();
    	createBlueToothView(views,context,isBlueToothActive);
    	//createDisplayView(views,context);
    	createMasterSyncAutomaticallyView(views,context);
    	createTaskView(views,context);
        return views;
    }

}
